import Queue from "./queue";

class Deque<T> extends Queue<T>{
    constructor(...args:T[]) {
        super(...args);
    }

    /**
     * 向队首追加
     */
    addFront(...args: T[]): void {
        if (!args.length) return;
        if (this.isEmpty()) {
            this.addBack(...args);
        }

        if (this.lastCurrent >= args.length) {
            for (let i = args.length - 1; i >= 0; i--) {
                this.lastCurrent--;
                this.items[this.lastCurrent] = args[i];
            }
        } else {
            const af_num = args.length - this.lastCurrent;
            this.itemsBack(af_num);
            this.addFront(...args);
        }
    }

    /**
     * item向后移动N位
     */
    itemsBack(num: number): void {
        for (let i = this.current - 1; i >= this.lastCurrent; i--) {
            this.items[i + num] = this.items[i]
        }
        this.current += num;
        this.lastCurrent += num;
    }

    /**
     * 向末尾追加
     */
    addBack(...args: T[]): void {
        this.enqueue(...args);
    }

    /**
     * 删除队首元素
     */
    removeFront(): T | undefined {
        return this.dequeue();
    }

    /**
     * 删除末尾元素
     */
    removeBack(): T | undefined {
        if (this.isEmpty()) return undefined;
        this.current--;
        let item = this.items[this.current];
        delete this.items[this.current];
        return item;
    }

    /**
     * 查看队首元素
     */
    peekFront() {
        return this.peek();
    }

    /**
     * 查看队尾元素
     */
    peekBack(): T | undefined {
        if (this.isEmpty()) return undefined;
        return this.items[this.current - 1];
    }

}



let deque = new Deque(1, 2, 3);
console.log("初始化成功, 查看长度", deque.size())
console.log("查看元素", deque.toString());
console.log("查看是否为空", deque.isEmpty());
deque.addFront(233, 2333);
console.log("向队首添加元素成功,查看长度", deque.size());
console.log("查看元素", deque.toString());
deque.addFront(2332, 23332);
console.log("向队首添加元素成功,查看长度", deque.size());
console.log("查看元素", deque.toString());

console.log("弹出队首元素", deque.removeFront());
console.log("弹出队首元素成功,查看长度", deque.size());

deque.addFront(2333, 23333);
console.log("向队首添加元素成功,查看长度", deque.size());
console.log("查看元素", deque.toString());
deque.addBack(12, 123);
console.log("向队尾添加元素成功,查看长度", deque.size());
console.log("查看元素", deque.toString());
console.log("弹出队首元素", deque.removeFront());
console.log("弹出队首元素成功,查看长度", deque.size());
console.log("查看元素", deque.toString());
console.log("弹出队尾元素", deque.removeBack());
console.log("弹出队尾元素成功,查看长度", deque.size());
console.log("查看元素", deque.toString());
console.log("查看此时队首元素", deque.peekFront());
console.log("查看此时队尾元素", deque.peekBack());
console.log("清空队列")
deque.clear();
console.log("查看长度", deque.size())
console.log("查看是否为空", deque.isEmpty());
